package client;

import java.io.*;
import java.net.*;

import data.*;
/**
 * this is the listener class. it a new thread for listening the message from the server
 * @author Bing Li; Kaidi Xu
 *
 */
public class Listener implements Runnable {

	private Client client;
	private ObjectInputStream input;
	private Socket sock;
	/**
	 * the constructor
	 * @param s the socket
	 * @param c the client thread reference 
	 * @throws IOException 
	 */
	public Listener(Socket s, Client c) throws IOException {

		sock = s;
		client = c;

		
	}
	/**
	 * the thread function
	 */
	@Override
	public void run() {
		Message m;
		try {
			input = new ObjectInputStream(sock.getInputStream());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		while (true) {
			try {
				m = (Message) input.readObject();

				if (m.getType() == data.Information.MESSAGE_TYPE_SENT_TO) {
					System.out.println(((TextMsg) m.getContent()).getContent());
					client.showMsg((TextMsg) m.getContent(),0,false);
				}
				if (m.getType() == data.Information.MESSAGE_TYPE_GROUP_SENT) {
					System.out.println(((TextMsg) m.getContent()).getContent());
					client.showMsg((TextMsg) m.getContent(),1,true);
				}

			} catch (IOException e) {
				break;
				// e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// break;
				e.printStackTrace();
			}
		}
	}

}
